package com.hsc.www.server.userAccount;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.Collection;

@Service
public class UserAccountService {


    private JdbcTemplate jdbcTemplate;


    @Autowired(required = false)
    private void createJdbcTemplate(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }


    public UserAccountEntity selectByUsername(String username) {
        String sql = "select id,username,password,age,sex,roles from t_user where username=?";
        Object args[] = new Object[]{username};
        UserAccountEntity userAccountEntity = jdbcTemplate.queryForObject(sql, args, createRowMapper());
        return userAccountEntity;

    }

    private RowMapper<UserAccountEntity> createRowMapper() {
        return (rs, rowNum) -> {
            UserAccountEntity u = new UserAccountEntity();
            u.setId(rs.getLong(1));
            u.setUsername(rs.getString(2));
            u.setPassword(rs.getString(3));
            u.setAge(rs.getInt(4));
            u.setSex(rs.getString(5));
            u.setRoles(JSONObject.parseObject(rs.getString(6), Collection.class));
            return u;
        };
    }

}


